//
//  UIView+QLXExt.m
//  fcuhConsumer
//
//  Created by 邱良雄 on 15/8/7.
//  Copyright (c) 2015年 avatar. All rights reserved.
//

#import "UIView+CYExt.h"
#include <objc/runtime.h>

@interface UIView()

@end

@implementation UIView(CYXExt)

/**
 *  生命周期构造
 */
-(void)addSubview_Ext:(UIView *)view{
    self.exclusiveTouch = true;// 防止多个按钮 同时按  同时回调点击事件
    [self addSubview_Ext:view];
    [view setNeedsLayout];
    if ([self.viewDelegate respondsToSelector:@selector(view:didAddSubview:)]) {
        [self.viewDelegate view:self didAddSubview:view];
    }
}

#pragma mark - 直接获取以及修改view的长宽xy等
/**********************直接获取以及修改view的长宽xy等**********************/
- (CGFloat)width
{
    return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(frame.origin.x, frame.origin.y, width, frame.size.height);
}
- (CGFloat)height
{
    return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
}
- (CGPoint)leftTop
{
    CGPoint result = CGPointMake(self.frame.origin.x, self.frame.origin.y);
    return result;
}
- (void)setLeftTop:(CGPoint)leftTop
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(leftTop.x, leftTop.y, frame.size.width, frame.size.height);
}
- (CGPoint)rightBottom
{
    CGPoint result = CGPointMake(self.frame.origin.x + self.frame.size.width, self.frame.origin.y + self.frame.size.height);
    return result;
}
- (void)setRightBottom:(CGPoint)rightBottom
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(rightBottom.x - frame.size.width, rightBottom.y - frame.size.height, frame.size.width, frame.size.height);
}
- (void)setLeft:(CGFloat)left
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(left, frame.origin.y, frame.size.width, frame.size.height);
}
- (CGFloat)left;
{
    return self.frame.origin.x;
}
- (void)setRight:(CGFloat)right
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(right - frame.size.width, frame.origin.y, frame.size.width, frame.size.height);
}
- (CGFloat)right
{
    return self.frame.origin.x + self.frame.size.width;
}
- (void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}
- (CGFloat)x
{
    return self.frame.origin.x;
}
- (void)setY:(CGFloat)y
{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}
- (CGFloat)y
{
    return self.frame.origin.y;
}
- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}
- (CGFloat)centerX
{
    return self.center.x;
}
- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}
- (CGFloat)centerY
{
    return self.center.y;
}
- (void)setSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}
- (CGSize)size
{
    return self.frame.size;
}
-(CGSize) getLayoutSize{
    [self setNeedsLayout];
    [self layoutIfNeeded];
    [self needsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    return [self systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
}
#pragma mark - 设置特殊Frame (加上导航栏高度)
/**********************设置特殊Frame (加上导航栏高度)**********************/
-(void)setFrame:(CGRect)orgFrame WithNavgBarHeight:(CGFloat)navbarHeight{
    self.frame = CGRectMake(orgFrame.origin.x,orgFrame.origin.y+navbarHeight, orgFrame.size.width,orgFrame.size.height);
}

#pragma mark - 手势相关
/**********************手势相关**********************/
-(UITapGestureRecognizer *) addTapGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:tap];
    return tap;
}

-(UIPanGestureRecognizer *) addPanGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:pan];
    return pan;
};

-(UIPinchGestureRecognizer *) addPinchGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UIPinchGestureRecognizer * pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:pinch];
    return pinch;
};

-(UISwipeGestureRecognizer *) addSwipeGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UISwipeGestureRecognizer * swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:swipe];
    return swipe;
};

-(UIRotationGestureRecognizer *) addRotationGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UIRotationGestureRecognizer * rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:rotation];
    return rotation;
};

-(UILongPressGestureRecognizer *) addLongPressGestureRecognizerWithTarget:(id)target action:(SEL) action{
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:target action:action];
    self.userInteractionEnabled = true;
    [self addGestureRecognizer:longPress];
    return longPress;
};

#pragma mark - 操控View层级
/********************************************操控View层级********************************************/
-(NSUInteger)getSubviewIndex{
    return [self.superview.subviews indexOfObject:self];
}
-(void)bringToFront{
    [self.superview bringSubviewToFront:self];
}
-(void)sendToBack{
    [self.superview sendSubviewToBack:self];
}
-(void)bringOneLevelUp{
    NSUInteger currentIndex = [self getSubviewIndex];
    [self.superview exchangeSubviewAtIndex:currentIndex withSubviewAtIndex:currentIndex+1];
}
-(void)sendOneLevelDown{
    NSUInteger currentIndex = [self getSubviewIndex];
    [self.superview exchangeSubviewAtIndex:currentIndex withSubviewAtIndex:currentIndex-1];
}
-(BOOL)isInFront
{
    return ([self.superview.subviews lastObject]==self);
}
-(BOOL)isAtBack{
    return ([self.superview.subviews objectAtIndex:0]==self);
}

-(void)swapDepthsWithView:(UIView*)swapView{
    [self.superview exchangeSubviewAtIndex:[self getSubviewIndex] withSubviewAtIndex:[swapView getSubviewIndex]];
}
-(void) hideSubViews{
    for (UIView * sub in self.subviews) {
        sub.hidden = true;
    }
}
-(void) showSubViews{
    for (UIView * sub in self.subviews) {
        sub.hidden = false;
    }
}
-(void) removeAllSubivews{
    for (UIView * view in self.subviews) {
        [view removeFromSuperview];
    }
}

#pragma mark - 伸缩视图
/********************************************伸缩视图********************************************/

-(void) scaleFrameOfSubviewsWithScale:(CGFloat)scale{
    for (UIView * sub in self.subviews) {
        CGRect frame = sub.frame;
        frame = CGRectMake(frame.origin.x * scale, frame.origin.y * scale, frame.size.width * scale, frame.size.height * scale);
        sub.frame = frame;
        //[sub addConstraintWithFrame:frame];
        if ([sub isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)sub;
            NSString * fontName = label.font.fontName;
            CGFloat pointSize = label.font.pointSize;
            label.font = [UIFont fontWithName:fontName size:pointSize * scale];
        }else if([sub isKindOfClass:[UIButton class]]){
            UIButton * button  = (UIButton *)sub;
            NSString * fontName = button.titleLabel.font.fontName;
            CGFloat pointSize = button.titleLabel.font.pointSize;
            button.titleLabel.font = [UIFont fontWithName:fontName size:pointSize * scale];
        }else {
            [sub scaleFrameOfSubviewsWithScale:scale];
        }
    }
}

-(void) scaleCenterOfSubviewsWithXScale:(CGFloat)xScale yScale:(CGFloat) yScale{
    for (UIView * sub in self.subviews) {
        CGRect frame = sub.frame;
        frame = CGRectMake(frame.origin.x * xScale, frame.origin.y * yScale, frame.size.width , frame.size.height );
        sub.frame = frame;
       // [sub addConstraintWithFrame:frame];
        if ([sub isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)sub;
            NSString * fontName = label.font.fontName;
            CGFloat pointSize = label.font.pointSize;
            label.font = [UIFont fontWithName:fontName size:pointSize * xScale];
        }else if([sub isKindOfClass:[UIButton class]]){
            UIButton * button  = (UIButton *)sub;
            NSString * fontName = button.titleLabel.font.fontName;
            CGFloat pointSize = button.titleLabel.font.pointSize;
            button.titleLabel.font = [UIFont fontWithName:fontName size:pointSize * xScale];
        }else {
            [sub scaleCenterOfSubviewsWithXScale:xScale yScale:yScale];
        }
    }
}
-(void)setScale:(CGFloat)scale{
    self.transform = CGAffineTransformMakeScale(scale, scale);
}
-(void)setRotation:(CGFloat)angle{
    self.transform = CGAffineTransformMakeRotation(angle);
}
-(void)setCornerWithRadius:(CGFloat)radius width:(float)width color:(UIColor *)color{
    self.layer.borderWidth = width;
    self.layer.borderColor = color.CGColor;
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = true;
}
-(void)setCornerWithWidth:(float)width color:(UIColor *)color{
    [self setCornerWithRadius:0 width:width color:color];
}
-(void) setCornerToCircleWidth:(float)width color:(UIColor *)color
{
    [self setCornerWithRadius:self.bounds.size.width/2 width:width color:color];
}
-(void) setCornerToCircle{
    CGFloat radius = self.bounds.size.width/2;
    [self setCornerWithRadius:radius];
}
-(void)setCornerWithRadius:(CGFloat)radius{
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = true;
}

#pragma mark - 其他
/********************************************其他********************************************/

- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
-(UINavigationController * ) navigationController{
    UIViewController * vc = [self viewController];
    while (vc && [vc isKindOfClass:[UINavigationController class]] == false) {
        vc = [vc.view.superview viewController];
    }
    return (UINavigationController *)vc;
}

-(UITabBarController * ) tabBarController{
    UIViewController * vc = [self viewController];
    while (vc && [vc isKindOfClass:[UITabBarController class]] == false) {
        vc = [vc.view.superview viewController];
    }
    return (UITabBarController *)vc;
}

// 进度 圆弧 百分比遮罩
-(void) arcProgressWithPercentage:(CGFloat) percentage{
    CAShapeLayer * mask = [self addArcProgressMaskLayer];//添加遮罩layer
    mask.path = [self getArcProgerssPathWithProgress:percentage].CGPath; //添加路径
}

-(CAShapeLayer * ) addArcProgressMaskLayer{
    static CAShapeLayer * mask ; //保证只会被添加一次
    if (!mask) {
        mask = [[CAShapeLayer alloc] init];
        mask.fillRule = kCAFillRuleEvenOdd;
        mask.lineWidth = 0.001;
        self.layer.mask = mask;
    }
    return mask;
}

-(UIBezierPath *) getArcProgerssPathWithProgress:(CGFloat) percentage{
    UIBezierPath * path = [[UIBezierPath alloc] init];
    CGSize size = self.frame.size;
    CGFloat startAngle = -M_PI_2;
    CGFloat endAngle = M_PI * 2 * percentage + startAngle;
    CGPoint center = CGPointMake(size.width/2, size.height/2);
    [path addArcWithCenter:center radius:size.width/2 startAngle:startAngle endAngle: endAngle clockwise:true];
    [path addLineToPoint:center];
    return path;
}

static char FirstEnterKey;
-(NSNumber *)firstEnter{
    return objc_getAssociatedObject(self, &FirstEnterKey);
}

-(void)setFirstEnter:(NSNumber *)firstEnter{
    objc_setAssociatedObject(self, &FirstEnterKey, firstEnter, OBJC_ASSOCIATION_RETAIN);
}

-(instancetype)initWithFrame_Ext:(CGRect)frame{
    self = [self initWithFrame_Ext:frame];
    //[self initSelf];
    return self;
}

-(void)removeFromSuperview_Ext{
    [self onExit];
    [self removeFromSuperview_Ext]; 
}

//下一帧调用 用来初始化一些数据  调用时机在init的下一帧后面 仅调用一次
-(void) onEnter{
//        self.layer.borderWidth = 1;
//        self.layer.borderColor = [UIColor redColor].CGColor;
}
//离开父亲
-(void) onExit{
    //self.firstEnter = nil;
}

//将UIView转成UIImage
-(UIImage *)getImageFromView:(UIView *)theView
{
    [theView setNeedsLayout];
    [theView layoutIfNeeded];
    [theView setNeedsDisplay];
    //UIGraphicsBeginImageContext(theView.bounds.size);
    CGSize size = CGSizeMake(theView.bounds.size.width  , theView.bounds.size.height  );
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(UIImage * ) getImage{
    return [self getImageFromView:self];
}

// Duplicate UIView
- (UIView*)duplicate:(UIView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}

-(UIView *)copySelf{
    return  [self duplicate:self];
}

/**
 *  view代理
 */
static char ViewDelegateKey;
-(id<UIViewDelegate>)viewDelegate{
    return objc_getAssociatedObject(self, &ViewDelegateKey);
}

-(void)setViewDelegate:(id<UIViewDelegate>)viewDelegate{
    objc_setAssociatedObject(self, &ViewDelegateKey, viewDelegate,OBJC_ASSOCIATION_ASSIGN);
}

static char NextLoopCallbackKey;

-(VoidClorse)nextLoopCallback{
    return objc_getAssociatedObject(self, &NextLoopCallbackKey);
}

-(void)setNextLoopCallback:(VoidClorse)nextLoopCallback{
    objc_setAssociatedObject(self, &NextLoopCallbackKey, nextLoopCallback, OBJC_ASSOCIATION_COPY);
}

-(void) performInNextLoopWithBlock:(VoidClorse) block{
    self.nextLoopCallback = nil;
    self.nextLoopCallback = block;
    [self setNeedsLayout];
}

+(instancetype) createFromXib{
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil                                                               options:nil];
    return  [nibContents objectAtIndex:0];
}

-(void)  setBackgroundWithImage:(UIImage *)image{
//    UIImageView * iv = [UIImageView create];
//    iv.image = image;
//    [self addSubview:iv];
//    [iv sendToBack];
//    iv.contentMode = UIViewContentModeScaleToFill;
//    [iv constraintWithEdgeZero];
}

// 增加触摸区域
static char TouchFrameAddEdgeKey;

-(UIEdgeInsets)touchFrameAddEdge{
    NSValue * value = objc_getAssociatedObject(self, &TouchFrameAddEdgeKey);
    if (value) {
        return [value UIEdgeInsetsValue];
    }
    return UIEdgeInsetsZero;
}

-(void)setTouchFrameAddEdge:(UIEdgeInsets)touchFrameAddEdge{
    NSValue * value = [NSValue valueWithUIEdgeInsets:touchFrameAddEdge];
    objc_setAssociatedObject(self, &TouchFrameAddEdgeKey, value, OBJC_ASSOCIATION_RETAIN);
}


@end
